<?php

namespace app\common\controller;

use think\facade\Cache;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\validate\CreateContacts as CreateContactsValidate;
use think\exception\ValidateException;
use app\common\model\PushMessage as PushMessageModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\Company as CompanyModel;
use app\common\model\ImContacts as ImContactsModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\Vip as VipModel;
use app\common\model\VipRuleValue as VipRuleValueModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\UserScore as UserScoreModel;
use XYCms\Im as XYCMSIm;

/**
 * 
 */
class Message extends Base
{
    public static function getList($D = [])
    {
        $where = [];
        $where[] = ['uid', '=', $D['uid']];
        $where[] = ['status', '=', 1];
        if (isset($D['is_read'])) {
            if ($D['is_read']) {
                $where[] = ['is_read', '=', 1];
            } else {
                $where[] = ['is_read', '=', 0];
            }
        }
        $Data = PushMessageModel::where($where)
            ->whereNull('delete_time')
            ->order('id desc')->paginate(15)->each(function ($v) {
                $v->friendly_time = friendly_time($v->create_time, 'friendly');
                return $v;
            });
        if ($Data->items()) {
            return parent::ajaxReturn('', MsgCode::$success, $Data);
        } else {
            return parent::ajaxReturn('暂无数据~', MsgCode::$error);
        }
    }
    public static function getFind($D)
    {
        $where = [];
        $where[] = ['msg.id', '=', $D['id']];
        $where[] = ['msg.uid', '=', $D['uid']];
        $where[] = ['msg.status', '=', 1];
        $Data = PushMessageModel::alias('msg')->where($where)
            ->whereNull('msg.delete_time')
            ->join(config('databse.prefix') . 'push_message_content content', 'content.mid=msg.id')
            ->field('msg.*,content.content')
            ->find();
        if ($Data) {
            if (!$Data->is_read)
                self::setMessageRead($D);
            return parent::ajaxReturn('', MsgCode::$success, $Data);
        } else {
            return parent::ajaxReturn('消息不存在', MsgCode::$error);
        }
    }
    public static function setMessageRead($D)
    {
        $where = [];
        $where[] = ['uid', '=', $D['uid']];
        if (!empty($D['id'])) {
            $where[] = ['id', '=', $D['id']];
            $PushMessageModel = PushMessageModel::where($where)->find();
            if ($PushMessageModel) {
                if ($PushMessageModel->is_read)
                    return parent::ajaxReturn();
                $PushMessageModel->is_read = 1;
                if ($PushMessageModel->save()) {
                    return parent::ajaxReturn();
                } else {
                    return parent::ajaxReturn('设置已读失败', MsgCode::$error);
                }
            } else {
                return parent::ajaxReturn('消息不存在', MsgCode::$error);
            }
        } else {
            if (PushMessageModel::where($where)->update(['is_read' => 1])) {
                return parent::ajaxReturn();
            } else {
                return parent::ajaxReturn('设置已读失败', MsgCode::$error);
            }
        }
    }
    public static function delMessage($D)
    {
        $where = [];
        $where[] = ['id', '=', $D['id']];
        $where[] = ['uid', '=', $D['uid']];
        $PushMessageModel = PushMessageModel::where($where)->find();
        if ($PushMessageModel) {
            $PushMessageModel->is_read = 1;
            $PushMessageModel->delete_time = time();
            if ($PushMessageModel->save()) {
                return parent::ajaxReturn();
            } else {
                return parent::ajaxReturn('删除失败', MsgCode::$error);
            }
        } else {
            return parent::ajaxReturn('消息不存在', MsgCode::$error);
        }
    }
    public static function createContacts($D)
    {
        /**
         * 用户验证
         */
        try {
            validate(CreateContactsValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(), MsgCode::$error);
        }
        $Data = [
            'touid'     => $D['touid'],
            'nickname'  => $D['nickname'],
            'headimg'   => $D['headimg'],
            'jobs_id'   => $D['jobs_id'],
            'send'      => [
                'nickname'  => $D['send']['nickname'],
                'headimg'   => $D['send']['headimg']
            ],
            'uid'       => $D['uid']
        ];
        $imObj = null;
        try {
            $imObj = new XYCMSIm;
            $Contacts = $imObj->getContacts($Data);
            if ($Contacts)
                return parent::ajaxReturn('', MsgCode::$success, $Contacts);
        } catch (\think\Exception $e) {
            return parent::ajaxReturn($e->getMessage(), MsgCode::$error);
        }
        $JobsModel = JobsModel::where(['id' => $D['jobs_id']])->find();
        if ($D['role_type']) {
            switch (config('xy_im_setting.company_mode')) {
                case 1:
                    if (!$D['company_id'])
                        return parent::ajaxReturn('请先完善企业信息', MsgCode::$company);
                case 2:
                    $ResumeModel = ResumeModel::alias('resume')->where(['resume.uid' => $D['touid']])
                        ->join('resume_downloaded d', 'd.resume_id=resume.id AND d.status=1 AND d.company_id=' . $D['company_id'], 'RIGHT')->field('d.id')->find();
                    if (!$ResumeModel)
                        return parent::ajaxReturn('您需要下载对方简历才能发起聊天', MsgCode::$error);
                    break;
                case 3:
                    $ret = self::hasImMaxPeople($D);
                    if ($ret)
                        return $ret;
                    break;
            }
        } else {
            $ResumeModel = ResumeModel::where(['uid' => $D['uid']])->find();
            switch (config('xy_im_setting.personal_mode')) {
                case 1:
                    if (!$ResumeModel)
                        return parent::ajaxReturn('请先完善简历信息', MsgCode::$resume);
                    $personal_mode_resume_progress = config('xy_im_setting.personal_mode_resume_progress');
                    if ($ResumeModel->progress < $personal_mode_resume_progress)
                        return parent::ajaxReturn('简历完整度低于' . $personal_mode_resume_progress . '%', MsgCode::$resume);
                    break;
                case 2:
                    $CompanyModel = CompanyModel::where(['uid' => $D['touid']])->find();
                    $JobsDeliveryResumeModel = JobsDeliveryResumeModel::where(['company_id' => $CompanyModel->id, 'resume_id' => $ResumeModel->id])->count();
                    if (!$JobsDeliveryResumeModel)
                        return parent::ajaxReturn('请先投递简历', MsgCode::$error);
                    break;
                case 3:
                    $ret = self::hasImMaxPeople($D);
                    if ($ret)
                        return $ret;
                    break;
            }
        }
        try {
            $Contacts = $imObj->createContacts($Data);
            if (!ImContactsModel::where(['uid' => $D['uid'], 'cid' => $Contacts['id']])->count()) {
                $UserVipModel = UserVipModel::where(['uid' => $D['uid']])->find();
                $UserVipModel->update_vip = 1;
                $ImContactsModel = new ImContactsModel;
                $ImContactsModel->cid = $Contacts['id'];
                $ImContactsModel->uid = $D['uid'];
                $ImContactsModel->save();
                $PushTaskModel = new PushTaskModel;
                $PushTaskModel->event       =   'IMMessage';
                $PushTaskModel->uid         =   $Data['touid'];
                $PushData = [
                    'nickname'  =>  $Data['send']['nickname'],
                    'jobs_name' =>  $JobsModel ? $JobsModel->title : '',
                    'time'      =>  date('Y-m-d H:i:s')
                ];
                $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
                Db::startTrans();
                try {
                    $UserVipModel->save();
                    $ImContactsModel->save();
                    $PushTaskModel->save();
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    //回滚事务
                    Db::rollback();
                }
            }
            return parent::ajaxReturn('', MsgCode::$success, $Contacts);
        } catch (\think\Exception $e) {
            return parent::ajaxReturn($e->getMessage(), MsgCode::$error);
        }
    }
    public static function hasImMaxPeople($D)
    {
        $where = ['is_company' => $D['role_type'], 'level' => 0];
        $UserVipModel = UserVipModel::where(['uid' => $D['uid']])->field('company_vip_level,company_vip_time,personal_vip_level,personal_vip_time')->find();
        if ($D['role_type']) {
            if ($UserVipModel && $UserVipModel->company_vip_time > time())
                $where = ['is_company' => $D['role_type'], 'level' => $UserVipModel->company_vip_level];
        } else {
            if ($UserVipModel && $UserVipModel->personal_vip_time > time())
                $where = ['is_company' => $D['role_type'], 'level' => $UserVipModel->personal_vip_level];
        }
        $VipModel = VipModel::where($where)->field('id')->find();
        if (!$VipModel)
            return parent::ajaxReturn('套餐异常，请联系客服', MsgCode::$vip);
        $imMaxPeople = VipRuleValueModel::where(['alias' => 'im-max-people'])->field('id,value')->find();
        if ($imMaxPeople) {
            $value = $imMaxPeople->value;
            $UserVipRuleModel = UserVipRuleModel::where(['uid' => $D['uid'], 'rid' => $imMaxPeople->id, 'status' => 1])->whereTime('expiry_time', '>', time())->sum('surplus_value');
            // 如果存在余量以余量为准，反之视为没有该权益
            if ($UserVipRuleModel) {
                $value = $UserVipRuleModel;
            } else {
                $value = 0;
            }
            $ImContactsModel = ImContactsModel::where(['uid' => $D['uid']])->count();
            if ($ImContactsModel >= $value)
                return parent::ajaxReturn('您的直聊套餐已用完，请开通套餐后使用', MsgCode::$vip);
        }
        $imMaxPeopleToday = VipRuleValueModel::where(['alias' => 'im-max-people-today'])->field('id,value')->find();
        if ($imMaxPeopleToday) {
            $value = $imMaxPeopleToday->value;
            $UserVipRuleModel = UserVipRuleModel::where(['uid' => $D['uid'], 'rid' => $imMaxPeopleToday->id, 'status' => 1])->whereTime('expiry_time', '>', time())->order('surplus_value desc')->find();
            if ($UserVipRuleModel) {
                $value = $UserVipRuleModel->surplus_value;
            }
            $ImContactsModel = ImContactsModel::where(['uid' => $D['uid']])->whereTime('create_time', 'today')->count();
            if ($ImContactsModel >= $value)
                return parent::ajaxReturn('今日发起沟通已达上限，请升级套餐或明日在发起沟通', MsgCode::$vip);
        }
        return false;
    }
    public static function getUnreadMessage($uid)
    {
        $where = [];
        $where[] = ['uid', '=', $uid];
        $where[] = ['status', '=', 1];
        $where[] = ['is_read', '=', 0];
        $count = PushMessageModel::where($where)->whereNull('delete_time')->count();
        return parent::ajaxReturn('', MsgCode::$success, ['message_count' => $count]);
    }
    public static function getUnreadMessageCate($uid)
    {
        $data = [
            'system' => [
                'tips' => '',
                'time' => '',
                'sum' => 0,
            ],
            'score' => [
                'tips' => '',
                'time' => '',
                'sum' => 0,
            ]
        ];
        $statusWhere = [];
        $statusWhere[] = ['uid', '=', $uid];
        $statusWhere[] = ['status', '=', 1];

        $count = PushMessageModel::where($statusWhere)->where(['is_read' => 0])->whereNull('delete_time')->count();
        $Find = PushMessageModel::where($statusWhere)->whereNull('delete_time')->order('id desc')->withAttr('create_time', function ($v, $data) {
            return friendly_time($v, 'friendly');
        })->find();
        if ($Find) {
            $data['system'] = [
                'tips' => $Find->desc,
                'time' => $Find->create_time,
                'sum' => $count,
            ];
        }
        $Find = UserScoreModel::where(['uid' => $uid])->order('id desc')->withAttr('create_time', function ($v, $data) {
            return friendly_time($v, 'friendly');
        })->find();
        if ($Find) {
            $data['score'] = [
                'tips' => $Find->desc,
                'time' => $Find->create_time,
                'sum' => 0,
            ];
        }
        return parent::ajaxReturn('', MsgCode::$success, $data);
    }

    /**
     * @Notes:发送消息时进行推送
     * @Author: hhm <huanghemao@exinyun.com>
     * @DateTime: 2022/2/19 0019 下午 18:36
     */
    public static function pushTaskMessage($D)
    {
        $PushTaskModel = new PushTaskModel;
        $PushTaskModel->event       =   'IMMessage';
        $PushTaskModel->uid         =   $D['touid'];
        if (empty($D['nickname'])) {
            $D['nickname'] = base64_decode(\app\common\model\UserInfo::where('uid', $D['senduid'])->value('nickname'));
        }
        $PushData = [
            'nickname'  =>  $D['nickname'],
            'jobs_name' =>  '',
            'time'      =>  date('Y-m-d H:i:s')
        ];
        $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
        $PushTaskModel->save();
    }
}
